import { useEffect, useState, useRef } from 'react';
import { apiCardDetailConvertOrder, apiCodeToOpenId, apiDecryptParam,apiGetHeadImg } from './api';
import Loading from './components/loading';
import main from './main';
import HomePage from './pages/homePage';
import { DetailJson } from './types';
import { lowerJSONKey, decryptData, parseLocationParams, encryptData } from './utils/utils';
let isWeixin = false;

export default function App() {
  let paramsRef = useRef<{ gid?: string; t?: string; uid?: string; iccid?: string }>();
  const [openId, setopenId] = useState<string>();
  const [errorText, seterrorText] = useState<string>();
  const [detailData, setdetailData] = useState<DetailJson | undefined>();
  const [iccid, seticcid] = useState<string>();
  useEffect(() => {
    // 地址栏数据
    let _location = parseLocationParams(window.location.search) ?? {};
    if (_location?.q) {
      decryptParam(_location.q);
    }
  }, []);
  // 解密
  async function decryptParam(_param: string) {
    let json = {};
    let res = await apiDecryptParam({ params: _param });
    let data = res.data;
    if (data.code === 200 && !!data.data) {
      json = lowerJSONKey(parseLocationParams(data.data));
      paramsRef.current = json;
    } else {
      let _urlParams = lowerJSONKey(parseLocationParams(decryptData(_param)));
      paramsRef.current = _urlParams;
    }
    let gId = paramsRef.current!.gid;
    if (gId) {
      // 获取主图接口
      getHeadImg();
    }
    if (paramsRef.current!.iccid!) {
      
      seticcid(paramsRef.current!.iccid);
    }
  }
  // 地址栏数据
  // let _location = parseLocationParams(window.location.search) ?? {};
  // let location = lowerJSONKey(_location);
  // console.log('转换后的地址栏数据---', location);
  useEffect(() => {
    // let _p = parseLocationParams(window.location.search) ?? {};
    // setlocation(_p);
    // console.log('_p', location);
    // seticcid(location.iccid);
    let ua = window.navigator.userAgent.toLowerCase();
    isWeixin = ua.includes('micromessenger');
    let uri = window.location.href;
    let redirect_uri = encodeURIComponent(uri);
    if (isWeixin && !window.location.search.includes('code') && !openId) {
      document.location.replace(
        `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${main.appId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
      );
    } else if (isWeixin && window.location.search.includes('code') && !openId) {
      let t = window.location.search.split('?')[1].split('&');
      let code = '';
      for (let s of t) {
        if (s.includes('code')) {
          code = s.split('=')[1];
          break;
        }
      }
      if (code) {
        main.code = code;
        getOpenId();
      }
    }
    if (openId) {
      main.openId = openId;
      setopenId(main.openId);
    }
    if (!isWeixin) {
      main.openId = '1';
      setopenId('1');
    }
  }, []); //eslint-disable-line

  useEffect(() => {
    if (!iccid) return;
    handUpdate();
  }, [iccid]); //eslint-disable-line

  // useEffect(() => {
  //   let gId = location.gid;
  //   if (gId) {
  //     // 获取主图接口
  //     getHeadImg();
  //   }
  // }, []);
  // useEffect(() => {
  //   // 地址栏数据
  //   let _location = lowerJSONKey(parseLocationParams(window.location.search) ?? {});
  //   if (_location?.q) {
  //     let _urlParams = lowerJSONKey(parseLocationParams(decryptData(_location.q)));
  //     paramsRef.current = _urlParams;
  //   } else {
  //     paramsRef.current = _location;

  //     // seturlParams(_location);
  //   }
  //   if (paramsRef.current!.iccid!) {
  //     seticcid(paramsRef.current!.iccid);
  //   }

  //   let gId = paramsRef.current!.gid;
  //   if (gId) {
  //     // 获取主图接口
  //     getHeadImg(paramsRef.current!.iccid);
  //   }
  // }, []);
  // 获取openId
  async function getOpenId() {
    try {
      let uri = window.location.href;
      let redirect_uri = encodeURIComponent(uri);
      let res = await apiCodeToOpenId(main.code!, main.appId, redirect_uri);
      let data = res.data;
      if (data.code === 200) {
        main.openId = data.data?.openid || data.data?.openId;
        setopenId(main.openId);
      }
    } catch (e) { }
  }

  // 获取主图
  async function getHeadImg() {
    try {
      let res = await apiGetHeadImg({
        convertType: paramsRef.current!.t,
        cardProductId: paramsRef.current!.gid,
        deptUserId: paramsRef.current!.uid,
        // iccid: iccid
      });
      let data = res.data;
      let _data = data.data || {};
      if (data.code === 200) {
        setdetailData({
          ..._data,
          businessJson: JSON.parse(_data.businessJson ?? '{}'),
        });
      } else {
        setdetailData({});
      }
    } catch (e) { }
  }

  async function getDetailConvertOrder(iccid: string) {
    // let _p = parseLocationParams(window.location.search) ?? {};
    try {
      let res = await apiCardDetailConvertOrder(
        Object.assign(
          {},
          {
            convertType: paramsRef.current!.t,
            deptUserId: paramsRef.current!.uid,
            cardProductId: paramsRef.current!.gid,
          },
          { iccid }
        )
      );
      let data = res.data;
      let _data = data.data || {};
      if (data.code === 200) {
        
        setdetailData({
          ..._data,
          businessJson: JSON.parse(_data.businessJson ?? '{}'),
        });

      } else if (data.code == -100) {
        if (_data.originalUrl) {
          window.location.href = _data.originalUrl;
        } else {
          let enCode = data.msg ? encryptData(`orderId=${data.msg}`) : "";
          window.location.href = `https://xbdl.zhisuoyi.net/hks/?q=${enCode}`;
        }
        
        
        setdetailData(undefined);
      } else {
        setdetailData(undefined);
        seterrorText(data.msg ?? '暂未查到改卡号相关信息');

      }
    } catch (e) { }
  }
  function handUpdate(iccid?: string) {
    if (paramsRef.current!.iccid || iccid) {
      let _iccid = paramsRef.current!.iccid ? paramsRef.current!.iccid : iccid;
      seticcid(_iccid);
      getDetailConvertOrder(_iccid!);
    }


  }
  if (!!errorText) {
    return (
      <div className="bw-100 bvh-100 d-flex-c ai-center jc-center">
        <div className="d-flex-c jc-center ai-center bw-100 pb-20">
          <img className="w-50 mb-20" src="./pic/icon_cancel.png" alt="" />
          <span className="ml-20 font-widget-600 font-size-20">{errorText}</span>
        </div>
      </div>
    );
  }
  if (!detailData && !errorText) {
    return (
      <Loading
        tips={'正在加载中...'}
        loadingClass="bh-100 overflow-hidden text-color-white d-flex-r ai-center jc-center mt-0 bg-shallow"
      />
    );
  }
  return <HomePage detailData={detailData!} location={paramsRef.current!} onUpdate={(i) => handUpdate(i)} />;
}
